package com.phison.fenestrapro.dashboard;

import java.io.BufferedWriter;
import java.io.IOException;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import com.vaadin.Application;
import com.vaadin.terminal.gwt.server.ApplicationServlet;
import com.vaadin.terminal.gwt.server.CommunicationManager;
import com.vaadin.terminal.gwt.server.SessionExpiredException;
import com.vaadin.terminal.gwt.server.WebApplicationContext;
import com.vaadin.ui.Window;

/**
 *
 * 
 * @author Niall O'Hara
 *
 */
public class FenestraProAppServlet extends ApplicationServlet {

	private static final long serialVersionUID = 1L;

	@Override
    protected void writeAjaxPageHtmlVaadinScripts(Window window,
            String themeName, Application application, BufferedWriter page,
            String appUrl, String themeUri, String appId,
            HttpServletRequest request) throws ServletException, IOException {
        page.write("<script type=\"text/javascript\">\n");
        page.write("//<![CDATA[\n");
        page.write("document.write(\"<script language='javascript' src='"+ themeUri + "/js/jquery-1.9.1.min.js'><\\/script>\");\n");
        page.write("document.write(\"<script language='javascript' src='"+ themeUri + "/js/html2canvas.js'><\\/script>\");\n");
        page.write("document.write(\"<script language='javascript' src='"+ themeUri + "/js/highcharts.js'><\\/script>\");\n");
        page.write("document.write(\"<script language='javascript' src='"+ themeUri + "/js/jquery.infieldlabel.min.js'><\\/script>\");\n");
        page.write("//]]>\n</script>\n");
        super.writeAjaxPageHtmlVaadinScripts(window, themeName, application,
                page, appUrl, themeUri, appId, request);
        
    }

	@Override
	public CommunicationManager createCommunicationManager(
			Application application) {
		return new SmartSessionCommunicationManager(application, this);
	}
	
	@Override
	protected void service(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

		try {
			Application existingApplication = getExistingApplication(request,
					false);
			if (existingApplication != null) {
				WebApplicationContext applicationContext = WebApplicationContext
						.getApplicationContext(request.getSession());
				SmartSessionCommunicationManager applicationManager = (SmartSessionCommunicationManager) applicationContext
						.getApplicationManager(existingApplication, this);
				if (!applicationManager.handleSmartSession(request, response,
						getRequestType(request) == RequestType.UIDL)) {
					return; // app termination request
				}
			}
		} catch (SessionExpiredException e) {
		}
		super.service(request, response);
	}
}
